package org.fork_join;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;
import java.util.concurrent.RecursiveTask;


public class ForkJoin extends RecursiveTask<Integer>{
	
	private static final int THRESHOLD = 2;
	
	private int start;
	
	private int end;
	
	public ForkJoin(int start,int end) {
		
		this.start = start;
		this.end = end;
	}
	
	@Override
	protected Integer compute() {
		int sum = 0;
		
		boolean canCompute = (end -start) <= THRESHOLD;
		if(canCompute){
			for(int i = start;i <= end;i++){
				sum +=  i;
			}
		}else{
			int middle = (start+end)/2;
			ForkJoin leftTask = new ForkJoin(start, middle);
			ForkJoin rightTask = new ForkJoin(middle, end);
			
			leftTask.fork();
			rightTask.fork();
			
			int leftResult = leftTask.join();
			
			int rightResult = rightTask.join();
			
			sum = leftResult + rightResult;
			
			
			
		}
		
		
		return sum;
	}
	
	
	public static void main(String[] args) {
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		ForkJoin forkJoin = new ForkJoin(1, 5);
		
		Future<Integer> result = forkJoinPool.submit(forkJoin);
		
		try {
			System.out.println(result.get());
		} catch (InterruptedException | ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
